package com.xunyin.modules.wechatshop.rest;


import com.github.pagehelper.util.StringUtil;
import com.xunyin.api.ApiResult;
import com.xunyin.api.XunyinException;
import com.xunyin.common.bean.LocalUser;
import com.xunyin.common.interceptor.AuthCheck;
import com.xunyin.enums.OrderStatusEnumV;
import com.xunyin.modules.mtorder.domain.MtOrder;
import com.xunyin.modules.mtorder.service.MtOrderService;
import com.xunyin.modules.mtorder.service.dto.OrderDto;
import com.xunyin.modules.user.domain.YxUser;
import com.xunyin.modules.user.service.YxUserService;
import com.xunyin.modules.user.service.dto.UserOrderDto;
import com.xunyin.modules.wechatshop.param.OrderListParam;
import com.xunyin.web.ResponseObject;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


//@RequestMapping(value = "/clientApi/order")
/**
 * 订单类controller
 * Copyright (C) 2022-2023
 * All rights reserved, Designed By www.tonetn.com
 * 注意：
 * 本软件为讯音云商开发研制，未经购买不得使用
 * 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 * 一经发现盗用、分享等行为，将追究法律责任，后果自负
 */
@Slf4j
@RestController
@Api(value = "购物车接口相关", tags = "共享空间:购物车接口相关")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ClientOrderController{

    private final YxUserService userService;
    /**
     * 订单服务接口
     * */
/*    @Autowired
    private OrderService orderService;*/

    private final MtOrderService mtOrderService;

/*    *//**
     * 获取我的订单列表
     *//*
    @RequestMapping(value = "/goods/order/list", method = RequestMethod.GET)
    @CrossOrigin
    public ApiResult<Object> list(HttpServletRequest request, @RequestParam Map<String, Object> param) {
        Long uid = LocalUser.getUser().getUid();
        YxUser user = userService.getById(uid.intValue());
        if (user == null) {
            throw new XunyinException("用户未登录");
        }
        param.put("userId", uid.intValue());
        ResponseObject orderData = mtOrderService.getUserOrderList(param);
        return ApiResult.ok(orderData.getData());
    }*/

    /**
     * 获取我的订单列表
     */
    @RequestMapping(value = "/goods/order/list", method = RequestMethod.POST)
    @CrossOrigin
    @AuthCheck
    public ApiResult<Object> list(HttpServletRequest request, @RequestBody OrderListParam orderListParam) {
/*        String token = request.getHeader("Access-Token");
        UserInfo userInfo = TokenUtil.getUserInfoByToken(token);

        if (userInfo == null) {
            return getFailureResult(1001, "用户未登录");
        }*/
        Long uid = LocalUser.getUser().getUid();
        YxUser user = userService.getById(uid.intValue());
        if (user == null) {
            throw new XunyinException("用户未登录");
        }
        orderListParam.setUserId(uid.toString());
        ResponseObject orderData = mtOrderService.getUserOrderList(orderListParam);
        return ApiResult.ok(orderData.getData());
        //return getSuccessResult(orderData.getData());
    }


    /**
     * 获取订单详情
     */
    @RequestMapping(value = "/order/detail", method = RequestMethod.GET)
    @CrossOrigin
    @AuthCheck
    public ApiResult<UserOrderDto> detail(HttpServletRequest request) {
/*        String token = request.getHeader("Access-Token");
        UserInfo userInfo = TokenUtil.getUserInfoByToken(token);

        if (userInfo == null) {
            return getFailureResult(1001, "用户未登录");
        }*/
        Long uid = LocalUser.getUser().getUid();
        YxUser user = userService.getById(uid.intValue());
        if (user == null) {
            throw new XunyinException("用户未登录");
            //return getFailureResult(1001, "用户未登录");
        }
        String orderId = request.getParameter("orderId");
        if (StringUtil.isEmpty(orderId)) {
            throw new XunyinException("订单不能为空");
            //return getFailureResult(2000, "订单不能为空");
        }

        UserOrderDto orderInfo = mtOrderService.getMyOrderById(Integer.parseInt(orderId));

        return ApiResult.ok(orderInfo);
        //return getSuccessResult(orderInfo);
    }

    /**
     * 取消订单
     */
    @RequestMapping(value = "/order/cancel", method = RequestMethod.GET)
    @CrossOrigin
    @AuthCheck
    public ApiResult<MtOrder> cancel(HttpServletRequest request) {
/*        String token = request.getHeader("Access-Token");
        UserInfo mtUser = TokenUtil.getUserInfoByToken(token);

        if (mtUser == null) {
            return getFailureResult(1001, "用户未登录");
        }*/
        Long uid = LocalUser.getUser().getUid();
        YxUser user = userService.getById(uid.intValue());
        if (user == null) {
            throw new XunyinException("用户未登录");
        }
        String orderId = request.getParameter("orderId");
        if (StringUtil.isEmpty(orderId)) {
            throw new XunyinException("订单不能为空");
            //return getFailureResult(2000, "订单不能为空");
        }

        UserOrderDto order = mtOrderService.getOrderById(Integer.parseInt(orderId));
        if (!order.getUserId().equals(uid.intValue())) {
            throw new XunyinException("订单信息有误");
            //return getFailureResult(2000, "订单信息有误");
        }

        MtOrder orderInfo = mtOrderService.cancelOrder(order.getId(), "会员取消");

        return ApiResult.ok(orderInfo);
        //return getSuccessResult(orderInfo);
    }

    /**
     * 确认收货
     */
    @RequestMapping(value = "/order/receipt", method = RequestMethod.GET)
    @CrossOrigin
    @AuthCheck
    public ApiResult<MtOrder> receipt(HttpServletRequest request) {
        Long uid = LocalUser.getUser().getUid();
        YxUser user = userService.getById(uid.intValue());
        if (user == null) {
            throw new XunyinException("用户未登录");
        }
        String orderId = request.getParameter("orderId");
        if (StringUtil.isEmpty(orderId)) {
            throw new XunyinException("订单不能为空");
            //return getFailureResult(2000, "订单不能为空");
        }

        UserOrderDto order = mtOrderService.getOrderById(Integer.parseInt(orderId));
        if (!order.getUserId().equals(uid.intValue())) {
            throw new XunyinException("订单信息有误");
            //return getFailureResult(2000, "订单信息有误");
        }

        OrderDto reqDto = new OrderDto();
        reqDto.setId(Integer.parseInt(orderId));
        reqDto.setStatus(OrderStatusEnumV.RECEIVED.getKey());
        MtOrder orderInfo = mtOrderService.updateOrder(reqDto);

        return ApiResult.ok(orderInfo);
        //return getSuccessResult(orderInfo);
    }

    /**
     * 获取待办订单
     */
    @RequestMapping(value = "/order/todoCounts", method = RequestMethod.GET)
    @CrossOrigin
    @AuthCheck
    public ApiResult<Map<String, Object>> todoCounts(HttpServletRequest request) {
/*        String token = request.getHeader("Access-Token");
        UserInfo userInfo = TokenUtil.getUserInfoByToken(token);*/
        Long uid = LocalUser.getUser().getUid();
        YxUser userInfo = userService.getById(uid.intValue());
        Map<String, Object> result = new HashMap<>();

        if (userInfo != null) {
            Map<String, Object> param = new HashMap<>();
            param.put("status", OrderStatusEnumV.CREATED.getKey());
            param.put("user_id", userInfo.getUid().intValue());
            List<MtOrder> data = mtOrderService.getOrderListByParams(param);
            result.put("toPay", data.size());
        }
        return ApiResult.ok(result);
        //return getSuccessResult(result);
    }
}
